import AdminModel from "../../dao/model/system/AdminModel";
import AdminEntity from "../../entities/system/AdminEntity";
import { IPageResponse } from "../../types/CommonType";
import { ValidationError } from "../../utils/errors";

export class AdminService {
  public static async add(admin: AdminEntity): Promise<true> {
    // 1. 转换类型
    admin = AdminEntity.transform(admin);

    // 2. 数据验证
    const errors = await admin.validateThis();
    if (errors.length > 0) {
      throw new ValidationError(errors[0]);
    }

    // 3. 添加到数据库
    await AdminModel.create(admin as any);
    return true;
  }

  /**
   * 分页获取数据
   * @param offset
   * @param limit
   * @param where
   * @returns
   */
  public static async findByPage(offset: number, limit: number, where?): Promise<IPageResponse> {
    let data = await AdminModel.findAndCountAll({
      offset,
      limit,
      where,
    });

    const result = {
      current: offset,
      total: data.count,
      size: limit,
      list: data.rows.map((item) => item.dataValues),
    };

    return result;
  }
}
